package controllers

import (
	//"log"

	"net/http"
	"xmgl/models"

	"github.com/astaxie/beego"
)

type LoginController struct {
	beego.Controller
}

type LogoutController struct {
	beego.Controller
}

func (this *LoginController) Get() {
	var (
	//result int
	)
	//models.Get_Session_User(this.Ctx)
	if this.GetSession("USER") == nil {
		//log.Println("default.go 没有取到session值，显示页面请用户登陆")
		this.TplName = "login.html"
		this.Data["Website"] = "请登陆"
	} else {
		//取到了cookie中name的值，跳转到首页
		http.Redirect(this.Ctx.ResponseWriter, this.Ctx.Request, "/", http.StatusFound)
	}
}

func (this *LoginController) Post() {
	var (
		user          models.Sut_user
		user_name     string
		user_password string
		err           error
	)
	user_name = this.GetString("user_name")
	user_password = this.GetString("user_password")
	//log.Println("用户登录，输入的user_name:", user_name, "\t user_password:", user_password)
	err = user.Login(user_name, user_password)
	//log.Println("验证用户登录，验证函数返回用户名：", user.User_name, "，用户ID：", user.User_id, "，err:", err)
	if err != nil {
		//认证失败
		this.Get()
		return
	}
	//认证成功，写入session
	this.SetSession("USER", models.Sut_user(user))

	/*sess := this.StartSession()
	sess.Set("USER", user)*/
	WebUserCount++ //用户总数加1
	//log.Println("default.go 登陆成功！用户总数：",WebUserCount,"跳转到首页")
	http.Redirect(this.Ctx.ResponseWriter, this.Ctx.Request, "/", http.StatusFound)
}

func (this *LogoutController) Get() {
	var (
		user models.Sut_user
	)
	//执行模块
	user.Logout(this.Ctx.ResponseWriter)
	//销毁session
	this.DelSession("USER")
	//用户总数减1
	WebUserCount--
	//log.Println("default.go 跳转到用户登陆页！用户总数：",WebUserCount)
	http.Redirect(this.Ctx.ResponseWriter, this.Ctx.Request, "/", http.StatusFound)
}
